package com.ztools.pc.service.impl.coupon;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztools.common.model.pc.coupon.CouponTemplate;
import com.ztools.common.util.common.PageUtil;
import com.ztools.common.util.pc.DictUtil;
import com.ztools.pc.async.CouponAsync;
import com.ztools.pc.mapper.coupon.CouponTemplateMapper;
import com.ztools.pc.service.coupon.CouponTemplateService;
import com.ztools.pc.service.sys.DictService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:seeTools
 * @Date: 2023/4/20  18:01
 * @Version 1.0
 */
@Transactional
@Service
public class CouponTemplateServiceImpl extends ServiceImpl<CouponTemplateMapper, CouponTemplate> implements CouponTemplateService {

    @Resource
    private DictService dictService;
    @Lazy
    @Resource
    private CouponAsync couponAsync;

    @Override
    public Page<CouponTemplate> findList(PageUtil<CouponTemplate> pageUtil) {
        List<OrderItem> orders = new ArrayList<>();
        QueryWrapper<CouponTemplate> queryWrapper = getQueryWrapper(pageUtil.getParams());
        Page<CouponTemplate> pages = new Page<>(pageUtil.getPage(), pageUtil.getSize());
        // 排序数据  StrUtil.toUnderlineCase huTools将驼峰装换为下划线格式
        orders.add(new OrderItem(StrUtil.toUnderlineCase(pageUtil.getSortName()), "asc".equals(pageUtil.getSortOrder())));
        pages.setOrders(orders);
        Page<CouponTemplate> page = page(pages, queryWrapper);
        dictionary(page.getRecords());
        return page;
    }

    @Override
    public boolean delete(CouponTemplate template) {
        boolean b = false;
        CouponTemplate userById = getById(template.getId());
        b = removeById(template.getId());
        couponAsync.refreshAllPacket();
        return b;
    }

    @Override
    public boolean add(CouponTemplate template) {
        return save(template);
    }

    @Override
    public boolean update(CouponTemplate template) {
        boolean b = false;
        // 修改前先获取，在删除（乐观锁）
        CouponTemplate templateById = getById(template);
        b = updateById(template);
        couponAsync.refreshAllPacket();
        return b;
    }

    @Override
    public List<CouponTemplate> findByObject(CouponTemplate template) {
        QueryWrapper<CouponTemplate> queryWrapper = new QueryWrapper<>();
        return list(queryWrapper);
    }

    @Override
    public List<CouponTemplate> getTemplate() {
        Date date = new Date();
        QueryWrapper<CouponTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().le(CouponTemplate::getStartDate, date)
                .gt(CouponTemplate::getEndDate, date);
        return list(queryWrapper);
    }

    @Override
    public String getNamesByIds(String ids) {
        QueryWrapper<CouponTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(CouponTemplate::getId, Collections.singletonList(ids));
        List<CouponTemplate> list = list(queryWrapper);
        List<String> couponList = list.stream().map(CouponTemplate::getName).collect(Collectors.toList());
        return String.join("&", couponList);
    }

    public QueryWrapper<CouponTemplate> getQueryWrapper(CouponTemplate template) {
        QueryWrapper<CouponTemplate> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(template.getName())) {
            queryWrapper.lambda().like(CouponTemplate::getName, template.getName());
        }
        if (StrUtil.isNotEmpty(template.getPurpose())) {
            queryWrapper.lambda().like(CouponTemplate::getPurpose, template.getPurpose());
        }
        if (template.getType() != null) {
            queryWrapper.lambda().eq(CouponTemplate::getType, template.getType());
        }
        if (StrUtil.isNotEmpty(template.getDaysLimit())) {
            queryWrapper.lambda().apply("FIND_IN_SET ('" + template.getDaysLimit() + "',days_limit)");
        }

        return queryWrapper;
    }

    /**
     * 字典翻译
     *
     * @param templateList 对象集合
     */
    public void dictionary(List<CouponTemplate> templateList) {
        for (CouponTemplate template : templateList) {
            dictionary(template);
        }
    }

    public void dictionary(CouponTemplate template) {
        if (template != null) {
            // 星期翻译
            if (StrUtil.isNotEmpty(template.getDaysLimit())) {
                template.setDaysLimitName(dictService.findByTypeCodes(DictUtil.WEEK, template.getDaysLimit()));
            }
            // 券类型翻译
            if (template.getType() != null) {
                template.setTypeName(dictService.findByTypeCode(DictUtil.COUPON_TYPE, template.getType() + ""));
            }
        }
    }

}
